Page({
  data: {
    posts: [],
    pageNum: 1,
    pageSize: 10,
    hasMore: true,
    loading: false,
    activeNavItem: 0,
    activeTab: 0,
    searchValue: '',
    searchFocus: false,
    showSearchPanel: false,
    searchHistory: [],
    currentFilter: 'all',
    suggestions: [],
    hotSearches: [
      { keyword: '前端开发', count: 1234 },
      { keyword: 'Python工程师', count: 998 },
      { keyword: '产品经理', count: 886 },
      { keyword: 'UI设计师', count: 754 },
      { keyword: '算法工程师', count: 665 }
    ],
    showFilterModal: false,
    filters: {
      sortBy: 'latest', // latest, popular, trending
      category: 'all',
      timeRange: 'all' // today, week, month, all
    },
    statusBarHeight: 0
  },

  onLoad() {
    this.loadPosts();
    this.loadSearchHistory();
    
    // 获取系统信息设置状态栏高度
    wx.getSystemInfo({
      success: (res) => {
        this.setData({
          statusBarHeight: res.statusBarHeight
        });
      }
    });
  },

  // 加载搜索历史
  loadSearchHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({ searchHistory: history });
  },

  // 保存搜索历史
  saveSearchHistory(keyword) {
    if (!keyword) return;
    
    let history = this.data.searchHistory;
    // 删除已存在的相同关键词
    history = history.filter(item => item !== keyword);
    // 将新关键词添加到开头
    history.unshift(keyword);
    // 只保留最近10条记录
    history = history.slice(0, 10);
    
    this.setData({ searchHistory: history });
    wx.setStorageSync('searchHistory', history);
  },

  // 清除搜索历史
  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清除搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({ searchHistory: [] });
          wx.removeStorageSync('searchHistory');
        }
      }
    });
  },

  // 搜索框输入
  onSearchInput(e) {
    const value = e.detail.value;
    this.setData({
      searchValue: value,
      showSearchPanel: true
    });
    
    if (value) {
      this.fetchSearchSuggestions(value);
    } else {
      this.setData({ suggestions: [] });
    }
  },

  // 获取搜索建议
  fetchSearchSuggestions: debounce(function(keyword) {
    // 模拟搜索建议
    const suggestions = [
      keyword + '工程师',
      keyword + '开发',
      keyword + '专家',
      '高级' + keyword,
      '资深' + keyword
    ];
    this.setData({ suggestions });
  }, 300),

  // 清除搜索
  clearSearch() {
    this.setData({
      searchValue: '',
      suggestions: [],
      showSearchPanel: true
    });
  },

  // 执行搜索
  onSearch() {
    const { searchValue } = this.data;
    if (!searchValue.trim()) {
      wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
      return;
    }

    this.saveSearchHistory(searchValue);
    this.setData({
      showSearchPanel: false,
      posts: [],
      pageNum: 1,
      hasMore: true
    });
    this.loadPosts(true);
  },

  // 搜索确认
  onSearchConfirm(e) {
    this.onSearch();
  },

  // 点击历史记录
  onHistoryItemTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchValue: keyword,
      showSearchPanel: false
    });
    this.onSearch();
  },

  // 点击热门搜索
  onHotSearchTap(e) {
    const keyword = e.currentTarget.dataset.keyword;
    this.setData({
      searchValue: keyword,
      showSearchPanel: false
    });
    this.onSearch();
  },

  // 点击搜索建议
  onSuggestionTap(e) {
    const suggestion = e.currentTarget.dataset.suggestion;
    this.setData({
      searchValue: suggestion,
      showSearchPanel: false
    });
    this.onSearch();
  },

  // 筛选切换
  onFilterTap(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({
      currentFilter: filter,
      posts: [],
      pageNum: 1,
      hasMore: true
    });
    this.loadPosts(true);
  },

  // 加载帖子数据
  async loadPosts(refresh = false) {
    if (this.data.loading || (!refresh && !this.data.hasMore)) return;
    
    this.setData({ loading: true });
    
    if (refresh) {
      this.setData({ pageNum: 1 });
    }

    try {
      // 模拟数据加载
      const { searchValue, currentFilter, filters } = this.data;
      
      // 这里应该调用实际的API
      const newPosts = [{
        id: Date.now(),
        avatar: 'https://cdn.example.com/images/avatar.png',
        name: "NAME",
        time: "1小时前",
        views: 32,
        likes: 0,
        isLiked: false,
        isCollected: false,
        tags: ["Python", "JAVA", "自学"],
        comments: [],
        images: [],
        location: '北京',
        category: '技术分享'
      }];

      this.setData({
        posts: refresh ? newPosts : [...this.data.posts, ...newPosts],
        pageNum: this.data.pageNum + 1,
        hasMore: newPosts.length === this.data.pageSize,
        loading: false
      });
    } catch (error) {
      this.setData({ loading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 显示筛选模态框
  showFilter() {
    this.setData({ showFilterModal: true });
  },

  // 应用筛选
  applyFilters(e) {
    const filters = e.detail;
    this.setData({
      filters,
      showFilterModal: false
    });
    this.loadPosts(true);
  },

  // 标签切换
  onTabClick(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeTab: index,
      posts: [],
      pageNum: 1,
      hasMore: true
    }, () => {
      this.loadPosts(true);
    });
  },

  // 导航切换
  onNavItemClick(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({ activeNavItem: index });
    
    switch(index) {
      case 0: // 首页
        this.loadPosts(true);
        break;
      case 1: // 搜索
        // 显示搜索页面
        wx.navigateTo({
          url: '/pages/search/search'
        });
        break;
      case 2: // 消息
        wx.navigateTo({
          url: '/pages/message/message'
        });
        break;
      case 3: // 我
        wx.navigateTo({
          url: '/pages/profile/profile'
        });
        break;
    }
  },

  // 查看图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset;
    wx.previewImage({
      urls,
      current
    });
  },

  // 查看位置
  viewLocation(e) {
    const { latitude, longitude, name } = e.currentTarget.dataset;
    wx.openLocation({
      latitude,
      longitude,
      name
    });
  },

  // 收藏操作
  onCollect(e) {
    const { index } = e.currentTarget.dataset;
    const posts = [...this.data.posts];
    posts[index].isCollected = !posts[index].isCollected;
    
    this.setData({ posts });
    wx.vibrateShort();
    
    // 保存到收藏列表
    if (posts[index].isCollected) {
      wx.setStorage({
        key: `collect_${posts[index].id}`,
        data: posts[index]
      });
    } else {
      wx.removeStorage({
        key: `collect_${posts[index].id}`
      });
    }
    
    wx.showToast({
      title: posts[index].isCollected ? '已收藏' : '已取消收藏',
      icon: 'success'
    });
  },

  // 点赞操作
  onLike(e) {
    const { index } = e.currentTarget.dataset;
    const posts = [...this.data.posts];
    posts[index].isLiked = !posts[index].isLiked;
    posts[index].likes += posts[index].isLiked ? 1 : -1;
    
    this.setData({ posts });
    wx.vibrateShort();

    // 发送点赞请求到服务器
    // this.updateLikeStatus(posts[index].id, posts[index].isLiked);
  },

  // 评论操作
  onComment(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '评论',
      editable: true,
      placeholderText: '请输入评论内容',
      success: (res) => {
        if (res.confirm && res.content) {
          const posts = [...this.data.posts];
          const newComment = {
            id: Date.now(),
            content: res.content,
            time: '刚刚',
            user: {
              name: '当前用户',
              avatar: 'https://cdn.example.com/images/avatar.png'
            }
          };
          posts[index].comments.push(newComment);
          this.setData({ posts });

          // 发送评论到服务器
          // this.submitComment(posts[index].id, newComment);
        }
      }
    });
  },

  // 回复评论
  replyComment(e) {
    const { postIndex, commentIndex } = e.currentTarget.dataset;
    const comment = this.data.posts[postIndex].comments[commentIndex];
    wx.showModal({
      title: `回复 ${comment.user.name}`,
      editable: true,
      placeholderText: '请输入回复内容',
      success: (res) => {
        if (res.confirm && res.content) {
          const posts = [...this.data.posts];
          const newReply = {
            id: Date.now(),
            content: res.content,
            time: '刚刚',
            user: {
              name: '当前用户',
              avatar: 'https://cdn.example.com/images/avatar.png'
            },
            replyTo: comment.user.name
          };
          if (!posts[postIndex].comments[commentIndex].replies) {
            posts[postIndex].comments[commentIndex].replies = [];
          }
          posts[postIndex].comments[commentIndex].replies.push(newReply);
          this.setData({ posts });
        }
      }
    });
  },

  // 分享操作
  onShareAppMessage(e) {
    const { from, target } = e;
    if (from === 'button') {
      const index = target.dataset.index;
      const post = this.data.posts[index];
      return {
        title: `${post.name}的动态`,
        path: '/pages/index/index?postId=' + post.id,
        imageUrl: post.images?.[0] // 如果有图片则使用第一张作为分享图
      };
    }
    return {
      title: '首页',
      path: '/pages/index/index'
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '发现更多精彩内容',
      query: 'from=timeline'
    };
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadPosts(true);
    wx.stopPullDownRefresh();
  },

  // 触底加载更多
  onReachBottom() {
    this.loadPosts();
  }
});

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func.apply(this, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}
